package com.cheng.xbjy.controller;

import com.alibaba.fastjson.JSONObject;
import com.cheng.xbjy.entity.User;
import com.cheng.xbjy.service.UserService;
import com.jfinal.kit.HttpKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/wx")
public class WxLoginController {


    @Autowired
    private UserService userService;

    @Value("${wx.redirect_uri}")
    private String redirect_uri;

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;

    @GetMapping("/toWxLogin")
    public void toWxLogin(HttpServletResponse response) throws IOException {
        //Step1：获取Authorization Code
        String url = "https://open.weixin.qq.com/connect/qrconnect?response_type=code " +
                "&appid=" + appId +
                "&redirect_uri=" + URLEncoder.encode(redirect_uri) +
                "&scope=snsapi_login";
        // 重定向到微信登录指定的地址进行微信登录授权,授权成功后返回code
        response.sendRedirect(url);
    }

    /**
     * 用户确认授权之后的操作
     * @throws IOException
     */
    @GetMapping("/wxLogin")
    public void wxLogin(HttpServletRequest request) throws IOException {
        // 用户扫码成功后携带过来的code
        String code = request.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId
                + "&secret=" + appSecret
                + "&code=" + code
                + "&grant_type=authorization_code";
        // 获取AccessToken、openid等数据
        String jsonString = HttpKit.get(url);

        JSONObject authInfo = JSONObject.parseObject(jsonString);

        String url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + authInfo.getString("access_token")
                + "&openid=" + authInfo.getString("openid");
        String info = HttpKit.get(url2);

        JSONObject userInfo = JSONObject.parseObject(info);

        // 根据微信的openid查询此用户原来有没有使用过微信登录
        User user = userService.findByWxOpenid(userInfo.getString("openid"));
        //判断用户是否是第一次登录
        if (user == null) {
            user = new User();
            // 用户的头像
            user.setPic(userInfo.get("headimgurl").toString());

            // 性别
            user.setGender(userInfo.get("sex").toString());
            // 用户的昵称
            user.setRealName(userInfo.get("nickname").toString());

            // 随机用户名(11位随机字符串)
            user.setUsername(UUID.randomUUID().toString().substring(36 - 15));

            // 注册时间为当前时间
            user.setRegisterTime(new Date());

            user.setWxOpenid(userInfo.get("openid").toString());
            // 注册一个新的用户
            userService.save(user);

            user = userService.findByWxOpenid(userInfo.get("openid").toString());
        }
//        session.setAttribute("userId", user.getId());
//
//        // 修改登录时间
//        userService.updateLoginTime(user.getId());
//        redisTemplate.opsForValue().set("loginUser:" + user.getId(), user, 7, TimeUnit.DAYS);
//
//        response.sendRedirect("/html/wx_login_info.html");
    }
}
